<template>
	<view class="deivceGoBack">
		<navBar :title="`${titleObj.navTitle}${titleObj.branchLineName ? '(' + titleObj.branchLineName + ')' : ''}`  || ''" @click="() => {uni.navigateBack()}"></navBar>
		<view class="content">
			<view class="center" @click="toNewDes">
				<text class="centerText">{{ titleObj.subTitle }}</text>
				<image class="img1" src="/subpackage-enginner/static/added.png" mode=""></image>
			</view>

		</view>
		<view class="rel_box">
			<u-tabs :list="tabList" @click="fnTabClick" :activeStyle="{color:'#2F80ED'}" :scrollable='false' itemStyle="padding:0 5px;height:44px"
				:lineWidth='120'></u-tabs>
			<view @click="fnReverse" class="arrow-box">
				<u-icon class="ssj" name="arrow-up-fill" :color="activeColor ? '#445469' : '#BFBFBF'" size="12"></u-icon>
				<u-icon class="xsj" name="arrow-down-fill" :color="!activeColor ? '#445469' : '#BFBFBF'" size="12"></u-icon>
			</view>
		</view>
		<!-- 历史未修复 -->
		<notRepaired v-if="tagIndex === 0" :dataList="notRepairedList" :titleName="titleObj.navTitle"></notRepaired>
		<!-- 新增 -->
		<added v-if="tagIndex === 1" :dataList="addList" :titleName="titleObj.navTitle"></added>
		<!-- 变更 -->
		<schange v-if="tagIndex === 2" :dataList="changeList" :titleName="titleObj.navTitle"></schange>
	</view>
</template>

<script>
	import ImageCompressor from '@/static/image-compressor.min.js';
	import Image from '@/static/image-compressor.min.js';
	import navBar from "@/components/navBar/navBar.vue"
	import notRepaired from "./components/notRepaired.vue"
	import added from "./components/added.vue"
	import schange from "./components/schange.vue"
	import {
		BS,
		BSM
	} from '@/session/index.js'
	import mixins from '@/utils/mixins.js'
	import {
		diseaseOrderGetList, //病害列表
		diseaseOrderGetDetails
	} from '@/api/engineeringMaintenance/engineeringMaintenance.js'

	import {
		doGet,
		doSave,
		doDelete
	} from "@/utils/offline/sqlite/index.js";
	//巡检的所有接口
	import * as XUNJIAN from '@/api/engineeringMaintenance/engineeringMaintenance.js'
	import {
		uploadImageFromBase64
	} from '@/utils/imageOperation.js'
	import {
		networkOnline
	} from '@/utils/offline/config';
	import {
		deleteImg
	} from '@/api/doc';
	// #ifdef APP-PLUS
	import {  registryTask  } from '@/utils/offline/listener';
	import siteInspectionTask from '@/utils/offline/task/siteInspection.js'
	// #endif
	export default {
		name: 'continueToPatrol',
		mixins: [mixins],
		components: {
			navBar,
			notRepaired,
			added,
			schange
		},
		data() {
			return {
				isLoading: false,
				tabList: [{
					name: '历史未修复',
					badge: {
						value: '',
						bgColor: '#2F80ED'
					}
				}, {
					name: '新增',
					badge: {
						value: '',
						bgColor: ''
					}
				}, {
					name: '变更',
					badge: {
						value: '',
						bgColor: ''
					}
				}],
				tagIndex: 0, //当前选中tab
				titleObj: {
					navTitle: '',
					subTitle: ''
				},
				notRepairedList: [],
				addList: [],
				changeList: [],
				activeColor: true,
			}
		},
		onLoad(params) {
			if (params && params.titleParams) {
				this.titleObj = JSON.parse(params.titleParams)
			}
			// console.log(BSM[BS.session1].lineObj,'--------')
		},
	    onShow() {
			this.getDataList()
			// #ifdef APP-PLUS
				registryTask(siteInspectionTask)
			// #endif
			// registryNetworkStateChange()
			// networkOnline()
			// doNetworkStateChange()
			// if(networkOnline()) {
			// 	await this.submitOfflineData
			// }
		},
		methods: {
			/**
			 * 提交离线数据操作 以下为伪代码
			 */
			/*
			//提交新增病害及其图片信息
			let newDiseases = select * from images where id is null //查询离线期间新增的病害数据(id为null)
			newDiseases.forEach(item => {
				let imgs = select * from images where docInfoId = item.docId
				let docId = await uploadImageFromBase64(imgs.dataList,imgs.dataBase64List)
				item.docId = docId
				doSave(item)
			})
			//提交历史病害变更信息及其图片信息
			let hisDiseases = select * from images where id is not null //查询离线期间新增的病害数据(id为null)
			hisDiseases.forEach(item => {
				let imgs = select * from images where docInfoId = item.docId and _id = ''
				await uploadImageFromBase64(imgs.dataList,imgs.dataBase64List)
				doSave(item)
			})
			*/
			async submitOfflineData() {
				if (!(await networkOnline())) {
					uni.showToast({
						title: '请保持网络连接再提交数据',
						icon: 'none',
						mask: true
					})
					throw new Error('请保持网络连接再提交数据')
				}
				// this.isLoading = true
				try {
					const DB = this.$store.getters.getDB
					//查询离线新增数据
					let newDiseases = await DB.select(`select * from diseases where _id = ''`)
					let taskSubmitNewDiseases = newDiseases.map(item => this.submitNewDisease(item))
					await Promise.all(taskSubmitNewDiseases)
					//查询离线操作的历史数据
					let hisDiseases = await DB.select(`select * from diseases where _id is not null`)
					let taskSubmitHisDiseases = hisDiseases.map(item => this.submitHistoryDisease(item))
					// //删除需要删除的离线图片数据到服务器
					let idsByimg = await DB.select(`select id from deletedImages where id > 0`)
					let taskDeleteImages = idsByimg.map(item => this.submitDelete(item.id))
					await Promise.all(taskSubmitHisDiseases)
					//提交完后清空数据库表并且关闭数据库
					await DB.clearTable(`diseases`)
					await DB.clearTable(`diseaseOrderLog`)
					await DB.clearTable(`diseaseGrade`)
					await DB.clearTable(`diseaseContent`)
					await DB.clearTable(`lastFillingRecord`)
					await DB.clearTable(`keywordsTable`)
					await DB.clearTable(`diseaseStatus`)
					await DB.clearTable(`repairTable`)
					await DB.clearTable(`images`)
					await DB.clearTable(`deletedImages`)
					await DB.close()
					// this.isLoading = false

				} catch (e) {
					console.error('submitOfflineData error', e, 165);
				}
			},
			async submitNewDisease(disease) {
				console.log(disease, '新增');

				try {
					if (disease.docId) {
						const DB = this.$store.getters.getDB
						let imgs = await DB.select(`select * from images where docInfoId = ${disease.docId} `)
						console.log(imgs, '163行');
						if (imgs.length === 0) return
						let {
							result: {
								id: docId
							}
						} = await uploadImageFromBase64({
							dataList: imgs[0].dataList,
							base64List: imgs.map(it => it.url.split(",")[1])
						})
						console.log(docId, '文档id');
						disease.docId = docId
					}
					let result = await doSave(XUNJIAN.diseaseOrderSave, {
						...disease,
						id: null
					})
					console.log('提交新增病害到服务器返回的结果', result);

				} catch (e) {
					console.error('submitNewDisease erroe', e);
				}
			},

			async submitHistoryDisease(disease) {
			 console.warn(disease, '000----0000');
				try {
					if (disease.docId) {
						const DB = this.$store.getters.getDB
						let imgs = await DB.select(
							`select * from images where docInfoId = ${disease.docId} and id < 0`)
						console.log(imgs, '210行');
						if (imgs.length === 0) return
						let {
							result: {
								id: docId
							}
						} = await uploadImageFromBase64({
							dataList: imgs[0].dataList,
							base64List: imgs.map(it => it.url.split(",")[1])
						})
						if (disease.docId < 0) {
							disease.docId = docId
						}
					}

					let result = await doSave(XUNJIAN.diseaseOrderSave, {
						...disease
					})
					console.log('提交历史未修复病害到服务器返回的结果', result);

				} catch (e) {
					console.error('submitHistoryDisease erroe', e);
				}
			},

			async submitDelete(id) {
				try {
					await deleteImg({
						id
					})
					console.log('提交删除图片数据到服务器返回的结果', result);

				} catch (e) {
					console.error('taskDelete erroe', e);
			 }
			},

			//新增病害
			toNewDes() {
				uni.navigateTo({
					url: `/subpackage-enginner/pages/engineeringMaintenance/on_site_inspection/components/newDiseases?titleParams=${JSON.stringify(this.titleObj)}`
				})
			},
			fnTabClick(val) {
				this.tabList.forEach(it => {
					it.badge.bgColor = ''
				})
				val.badge.bgColor = '#2F80ED'
				this.tagIndex = val.index
			},
			//病害列表
			async getDataList() {
				const ownerCode = uni.getStorageSync('ownerCode')
				let params_data = JSON.parse(uni.getStorageSync('lineData'))
				let resq_params = {
					currPage: 1,
					pageSize: 10000,
					params: params_data
				}
				this.$set(resq_params.params, 'type', 'inspect')
				this.$set(resq_params.params, 'isOffine', true)
				this.$set(resq_params.params, 'projectId', uni.getStorageSync('isOwner'))
				doGet(XUNJIAN.diseaseOrderGetList, resq_params)
					.then(res => {
						console.log(res, '表格内容列表')
						if (res.success) {
							//未修复数据
							const list = res.result.list.filter(item => item.orderType === 'history_not_repaired')
							console.log(list,ownerCode);
							this.notRepairedList = list
							//0417杭港定制化需求对应pingcode  CDS-1270
							if(ownerCode !== 'hg') {
								this.notRepairedList = list.filter(it => it.diseaseChange !== 'selfcure')
							}
							console.log(this.notRepairedList,'过滤');
							this.tabList[0].badge.value = this.notRepairedList.length
							//新增
							this.addList = res.result.list.filter(item => item.orderType === 'add')
							this.tabList[1].badge.value = this.addList.length
							//变更
							this.changeList = res.result.list.filter(item => item.orderType === 'change')
							this.tabList[2].badge.value = this.changeList.length
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none'
							})
						}
					})
			},
			fnReverse() {
				this.activeColor = !this.activeColor
				this.notRepairedList = this.notRepairedList.reverse()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.deivceGoBack {
		position: relative;
		/* #ifdef MP-WEIXIN */
			padding-top: 200rpx;
		/* #endif */
		.content {
			background-color: #F5F7FA;
			padding-top: 32rpx;

			.center {
				// height: 200rpx;
				font-size: 36rpx;
				font-family: PingFang SC-Bold, PingFang SC;
				font-weight: bold;
				color: #445469;
				// line-height: 42rpx;
				background-color: #FFFFFF;
				padding: 42rpx 28rpx;
				position: relative;

				.centerText {
					height: 50rpx;
					font-size: 36rpx;
					font-family: PingFang SC-Heavy, PingFang SC;
					font-weight: 800;
					color: #FFFFFF;
					line-height: 42rpx;
					position: absolute;
					z-index: 10;
					top: 80rpx;
					left: 52rpx;
				}

				.img1 {
					width: 684rpx;
					height: 182rpx;
				}
			}
		}

		.rel_box {
			position: relative;

			// .ssj {
			// 	position: absolute;
			// 	left: 228rpx;
			// 	top: 24rpx;
			// }

			// .xsj {
			// 	position: absolute;
			// 	top: 40rpx;
			// 	left: 228rpx;
			// }

		}
		.arrow-box {
			position: absolute;
			top: 24rpx;
			left: 230rpx;
			display: flex;
			flex-direction: column
		}




	}

	/deep/ .u-badge--error {
		background-color: #9d9595;
	}
</style>
